using Consul;
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// 配置Serilog
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .WriteTo.Elasticsearch(new Serilog.Sinks.Elasticsearch.ElasticsearchSinkOptions(new Uri("http://elasticsearch:9200"))
    {
        AutoRegisterTemplate = true,
        AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7
    })
    .CreateLogger();

builder.Host.UseSerilog();

// 添加服务到容器
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// 配置Consul客户端
builder.Services.AddSingleton<IConsulClient>(provider =>
{
    var consulConfig = new ConsulClientConfiguration
    {
        Address = new Uri(builder.Configuration["Consul:Address"] ?? "http://consul:8500")
    };
    return new ConsulClient(consulConfig);
});

// 配置健康检查
builder.Services.AddHealthChecks();

// 配置CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

var app = builder.Build();

// 配置HTTP请求管道
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseCors("AllowAll");

// 配置健康检查端点
app.MapHealthChecks("/health");

app.MapControllers();

// 注册服务到Consul
var consulClient = app.Services.GetRequiredService<IConsulClient>();
var serviceId = $"productservice-{Environment.MachineName}";
var serviceName = "ProductService";
var servicePort = int.Parse(builder.Configuration["ServicePort"] ?? "5003");
var serviceAddress = Environment.GetEnvironmentVariable("SERVICE_HOST") ?? "localhost";

var registration = new AgentServiceRegistration
{
    ID = serviceId,
    Name = serviceName,
    Address = serviceAddress,
    Port = servicePort,
    Tags = new[] { "api", "products" },
    Check = new AgentServiceCheck
    {
        HTTP = $"http://{serviceAddress}:{servicePort}/health",
        Interval = TimeSpan.FromSeconds(10),
        Timeout = TimeSpan.FromSeconds(5),
        DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1)
    }
};

try
{
    await consulClient.Agent.ServiceRegister(registration);
    Log.Information("产品服务已注册到Consul");
}
catch (Exception ex)
{
    Log.Error(ex, "注册服务到Consul失败");
}

// 应用关闭时注销服务
app.Lifetime.ApplicationStopping.Register(async () =>
{
    try
    {
        await consulClient.Agent.ServiceDeregister(serviceId);
        Log.Information("产品服务已从Consul注销");
    }
    catch (Exception ex)
    {
        Log.Error(ex, "从Consul注销服务失败");
    }
});

try
{
    Log.Information("启动产品服务...");
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "产品服务启动失败");
}
finally
{
    Log.CloseAndFlush();
} 